<template>
	<view class="filter-model">
		<view class="model-content" @click="showFuc">
			<view class="imgBox">

				<image src="@/static/images/index/selectA.png" mode="" v-if="activtTxt"></image>
				<image src="@/static/images/index/selectD.png" mode="" v-else></image>
			</view>
			<view class="model-content-title" :style="{ color: activtTxt ? '#0091ff' : '#333' }">{{ '筛选'}}</view>
		</view>

		<filter-drawer :chooseData="choosed" :filterList="filterList" :comfireText="comfireText" :show="showFilter"
			:keyMap="keyMap" title="电梯筛选" :isShowDate="isShowDate" ref="filter-drawer" @closed="handleClose"
			@submit="submitFilter" @chooseTag="getResultCount"></filter-drawer>
	</view>
</template>

<script>
// import filterDrawer from './filter/filterDrawer.vue';
import filterDrawer from '@/components/filter-drawer/filterDrawer.vue';
import { getBrand, driveMode } from '@/apis/barrierSearch.js';
import { myElevator, deptElevatorList } from '@/apis/project.js';
import { removeEmpty } from '@/utils/utils.js';
export default {
	name: 'filter-model',
	components: { filterDrawer },
	props: {
		disabled: {
			type: Boolean,
			default: false
		},
		all: {
			type: Boolean,
			default: true
		},
		csd: {
			type: Object,
			default: () => {
				return {};
			}
		},
		// elevatorId:{
		// 	type:String
		// },
		dateOpt: {
			type: Object
		},
		userId: {
			type:  [String,Number]
		},
		buildingId: {
			type:  [String,Number]
		},
		keyword: {
			type: String
		},
		eltabIdx: {
			type: [String,Number]
		},
		tabIdx: {
			type:  [String,Number]
		},
		eleClassify: {
			type: String
		}
	},
	data() {
		return {
			filterList: [{ key: 'useTypes', title: '年审', list: [{ name: '年审', value: 0 }, { name: '非年审', value: 1 }] }],
			choosed: {},
			showFilter: false,
			allChecked: true,
			chooseArr: [],  // 选中的标签arr
			comfireText: '确定',
			keyMap: {},
			isShowDate: false,
			// startTime:'',
			// isShowTemplate:true,
			dateObj: {
				startTime: '',
				endTime: '',
				value: ''
			},
			activtTxt: false
		};
	},
	created() {
		// this.initModel();
		this.allChecked = this.all;
		this.choosed = this.csd;
		this.activtTxt = Object.keys(this.choosed).length ? true : false;
		// 给日期组件赋值

		setTimeout(() => {
			this.setChooseArr();
		}, 500);
		this.getFilterData();
	},
	computed: {

		showConditions() {
			// console.log(this.choosed,this.csd,666)
			let flag = false;
			flag = this.allChecked || Object.keys(this.choosed).length === 0 ? true : false;
			return flag;
		}
	},
	watch: {
		// csd(value,old) {
		// 	this.choosed = value
		// 	console.log(this.choosed ,'带过去的值')
		// }
		showFilter(val) {
			this.$emit('showFilterChange', val);
		},
		eltabIdx(val) {
			this.choosed = {};
			this.comfireText = '完成';
		},
		tabIdx(val) {
			this.choosed = {};
			this.comfireText = '完成';
		}
	},
	methods: {

		async getFilterData() {
			const all = [driveMode(), getBrand()];
			await Promise.all(all).then(res => {
				if (res) {
					let arr1 = res[0].data.map(item => {
						return { name: item.name, value: item.id };
					});
					console.log(arr1, 5525);
					let arr2 = res[1].data.map(item => {
						return {
							name: item.brandName,
							value: item.id
						};
					});
					this.filterList.push(
						{
							title: '设备品种',
							key: 'modeIds',
							list: arr1
						},
						{
							title: '品牌',
							key: 'brandIds',
							list: arr2
						}
					);
				}
			});
			console.log(this.filterList, 66666);
			this.setKeyMap(this.filterList);
		},
		// 关闭操作
		handleClose() {
			this.showFilter = false;
			let obj = {};
			this.chooseArr.forEach(item => {
				if (obj[item.key]) {
					obj[item.key].push(item.value);
				} else {
					obj[item.key] = [];
					obj[item.key].push(item.value);
				}
			});
			this.choosed = obj;

			// 日期父组件接受日期默认值

			this.$nextTick(() => {
				this.$refs['filter-drawer'].initData(obj, this.dateObj);
			});
		},
		// 打开对话框
		showFuc() {
			console.log('打开对话框');
			if (this.disabled) {
				return;
			}

			setTimeout(() => {
				this.showFilter = true;
				// 初始化组组件
				console.log(this.choosed, 5555);
				this.$refs['filter-drawer'].initData(this.choosed, this.dateObj);

				// let obj={allChecked:this.allChecked,choosed:this.choosed,...this.dateObj}

				// this.handleCount(obj)
			}, 800);
		},
		// 完成筛选
		filterd(res) {
			this.$emit('filterd', {
				choosed: this.choosed,
				allChecked: this.allChecked,
				dateObj: res.dateObj
			});
		},
		// 接受父组件保存按钮的操作
		submitFilter(res) {
			this.keyMap = res.keyMap;
			// console.log(this.keyMap, 222);
			this.allChecked = res.allChecked;
			this.choosed = res.choosed;
			// console.log(Object.keys(this.choosed).length ,'选中的值');
			this.activtTxt = Object.keys(this.choosed).length ? true : false;
			this.showFilter = false;
			this.setChooseArr();
			this.filterd(res);
		},

		// 删除筛选item
		removeItem(item, index) {
			// console.log(222);
			// this.showFilter=true
			this.showFuc();
			return;
		},

		// 渲染已选标签
		setChooseArr() {
			let filterList = this.filterList;
			if (this.allChecked) {
				this.chooseArr = [];
				return;
			}
			let arr = [];
			for (let key in this.choosed) {
				let obj = this.filterList.find((item, i) => {
					return item.key === key;
				});
				console.log(obj, 'obj的值set的值');
				if (obj) {
					obj.list.forEach(e => {
						if (this.choosed[key].indexOf(e.value) != -1) {
							arr.push({
								...e,
								key
							});
						}
					});
				}
			}

			this.chooseArr = arr;
			// console.log(this.chooseArr, 'this.chooseArr');
		},

		setKeyMap(list) {
			const map = new Map();
			list.forEach(item => {
				map.set(item.key, { flag: false });
			});
			const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value), obj), {});
			// console.log(obj, 'flagMap');
			this.keyMap = obj;
		},

		getListTotal(obj) {
			if (this.eltabIdx == 0) {
				return new Promise((resolve, reject) => {
					deptElevatorList(obj)
						.then(res => {
							if (res) {
								resolve(res.data);
							}
						})
						.catch(() => {
							resolve({});
						});
				});
			} else {
				return new Promise((resolve, reject) => {
					myElevator(obj)
						.then(res => {
							if (res) {
								resolve(res.data);
							}
						})
						.catch(() => {
							resolve({});
						});
				});
			}
		},
		// 点击标签的时候
		getResultCount(res) {
			this.startTime = res.startTime;
			this.handleCount(res);
		},
		// 获取点击筛选条件后的数量总数
		async handleCount(res) {
			const { allChecked, choosed, startTime, endTime } = res;

			// if (!allChecked && !Object.keys(choosed).length && !startTime) {
			// 	this.comfireText = '确定';
			// 	return;
			// }
			let params = {
				userId: this.userId,
				buildingId: this.buildingId,
				keyword: this.keyword,
				eleClassify: this.eleClassify
			};
			let query = {};
			// if (Object.keys(choosed).length || allChecked) {
			if (Object.keys(choosed).length) {
				const map = new Map();

				for (let key in choosed) {
					map.set(key, choosed[key]);
				}
				const obj = [...map.entries()].reduce((obj, [key, value]) => ((obj[key] = value.join(',')), obj), {});

				query = obj;
			}

			const tempList = ['userId', 'buildingId', 'keyword'];
			let tempParams = Object.keys(choosed).length ? { ...query, ...params } : params;

			for (let key in tempParams) {
				if (!tempList.includes(key) && key != 'eleClassify') {
					tempParams[key] = tempParams[key].split(',');
				}
			}
			// console.log(params);

			// 获取请求的数据
			let count = await this.getListTotal(removeEmpty(tempParams));

			// console.log(count,"数值");
			if (count.length > 0) {
				this.comfireText = `查看${count.length}条数据`;
			} else {
				uni.showToast({
					icon: 'none',
					title: '筛选结果为空 请重新选择条件'
				});
				this.comfireText = '完成';
			}
			// }
		}
	}
};
</script>

<style lang="scss" scoped>
.filter-model {
	width: 100%;

	.imgBox {
		display: flex;

		image {
			width: 32rpx;
			height: 32rpx;
		}
	}

	.model-content {
		display: flex;
		font-size: 26rpx;
		color: #333;
		align-items: center;
		justify-content: flex-end;

		&-title {
			display: flex;
			// font-weight: bold;
			letter-spacing: 1rpx;
			align-items: center;
			margin-right: 10rpx;

			image {
				width: 22rpx;
				height: 22rpx;
				transition: 0.3s all;
				margin: 4rpx 0rpx 0 7rpx;
			}

			.line {
				width: 2rpx;
				height: 30rpx;
				background-color: #ccc;
				margin-left: 12rpx;
			}
		}

		&-all {
			font-size: 24rpx;
			color: #999;
			margin-left: 12rpx;
		}

		&-tags {
			flex: 1;
			display: flex;
			flex-wrap: wrap;

			&-item {
				border: 2rpx solid #cccccc;
				padding: 0 4rpx 2rpx 8rpx;
				color: #666;
				border-radius: 4rpx;
				margin: 10rpx;
				font-size: 24rpx;

				image {
					width: 20rpx;
					height: 20rpx;
				}
			}
		}
	}
}
</style>
